<?php
/**
 * Created by PhpStorm.
 * User: songs
 * Date: 2019/11/20
 * Time: 10:14
 */

namespace App\Services\Api;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\Admin\CompanyModel;
use App\Models\Admin\JobModel;
use App\Models\Admin\JobStaffModel;
use App\Models\Admin\OrderBaleModel;
use App\Models\Admin\OrderCheckModel;
use App\Models\Admin\OrderTempModel;
use App\Models\Admin\StaffModel;
use App\Models\JobsCompanysModel;
use App\Models\JobsModel;
use App\Models\LogModel;
use App\Models\OrderCommentModel;
use App\Models\UploadPicModel;
use App\Models\User\UserLevelModel;
use App\Models\User\UserModel;
use App\Models\UserStaffModel;
use App\Models\UserStaffOptionModel;
use App\Services\Jiguang\JMessageApi;
use App\Services\OrdersPayService;
use App\Utilities\Imgcompress;
use Illuminate\Http\Request;
use App\Models\MoneyBilModel;
use DB;
use App\Models\User\UserOrdersModel;
use App\Services\Msg\MsgService;

/// App\Services\Api\Job@
class Job extends ApiBase
{

    /**
     * 我的应聘列表
     */
    public function myyingpin(Request $request)
    {
        $page = $request->post('page');
        $listid = JobStaffModel::where(['uid' => OA::$user->getId()])
            ->select(['origin_id', 'id', 'status', 'cid'])
            ->orderBy('id', 'desc')
            ->skip($page * 10)
            ->take(10)
            ->get();
        $dataArr = [];
        foreach ($listid as $key => $vo) {
            $model = JobsCompanysModel::where([
                'id' => $vo['origin_id']
            ])->select([
                'cid', 'job', 'contact_name', 'address', 'emolument', 'id', 'company_name'
            ])
                ->first();
            $user = UserModel::where('id', $model->cid)->select(['head', 'name'])->first();
            //   $com = CompanyModel::where('uid',$model->cid)->first();
            $jobModel = JobModel::where('id', $model->job)->first();
            $dataArr[$key]['id'] = $model->id;
            $dataArr[$key]['cid'] = $vo->cid;
            $dataArr[$key]['jiguang_id'] =JMessageApi::idToJiguang($vo->cid);
            $dataArr[$key]['yingpin_id'] = $vo->id;
            $dataArr[$key]['cname'] = $user->name;
            $dataArr[$key]['contact'] = $model->contact_name;
            $dataArr[$key]['jobName'] = $jobModel ? $jobModel->name : '未知岗位';
            $dataArr[$key]['address'] = $model->address;
            $dataArr[$key]['emolument'] = $model->emolument;
            $dataArr[$key]['company_name'] = $model->company_name;
            $dataArr[$key]['status_str'] = JobStaffModel::getStatus($vo->status);
            $dataArr[$key]['status'] = $vo->status;
            if ($user && $user->head) {
                $dataArr[$key]['head'] = Fun::pImg($user->head);
            } else {
                $dataArr[$key]['head'] = '';
            }
        }
        OA::Json(0, $dataArr);
    }

    /**
     * 我的招聘列表
     */
    public function myzhaopin(Request $request)
    {
        $page = $request->post('page');
        $listid = JobsCompanysModel::where([
            'cid' => OA::$user->getId(),
            'del' => 0
        ])->select([
            'cid', 'job', 'contact_name', 'address', 'emolument',//
            'id', 'created_at', 'num', 'age_range', 'education', 'company_name', 'status',
            'cid'
        ])
            ->orderBy('status', 'asc')
            ->orderBy('id', 'desc')
            ->skip($page * 10)
            ->take(10)
            ->get();
        $uid = OA::$user->getId();
        $dataArr = [];
        foreach ($listid as $key => $model) {
            $user = UserModel::where('id', $model->cid)->select(['head', 'name'])->first();
            $jobModel = JobModel::where('id', $model->job)->first();
            $dataArr[$key]['id'] = $model->id;
            $dataArr[$key]['uname'] = $user->name;
            $dataArr[$key]['contact'] = $model->contact_name;
            $dataArr[$key]['created_at'] = Fun::date($model->created_at);
            $dataArr[$key]['num'] = $model->num;
            $dataArr[$key]['yingpinrenshu'] = JobStaffModel::where('origin_id', $model->id)->count();
            $dataArr[$key]['jobName'] = $jobModel ? $jobModel->name : '未知岗位';
            $dataArr[$key]['address'] = $model->address;
            $dataArr[$key]['emolument'] = '¥' . $model->emolument;
            $dataArr[$key]['education'] = UserStaffModel::educationTo($model->education);//学历
            $dataArr[$key]['age_range'] = $model->age_range;
            $dataArr[$key]['company_name'] = $model->company_name;

            $dataArr[$key]['cid'] = $model->cid;
            $dataArr[$key]['isme'] = $model->cid == $uid;
            $dataArr[$key]['status'] = $model->status;
            $dataArr[$key]['status_src'] = JobsCompanysModel::getStatus($model->status);
            if ($user && $user->head) {
                $dataArr[$key]['head'] = Fun::pImg($user->head);
            } else {
                $dataArr[$key]['head'] = '';
            }
        }
        OA::Json(0, $dataArr);
    }

    /**
     * 删除自己发布的应聘信息
     */
    public function deleteyingpin(Request $request)
    {
        $id = $request->post('id');
        $del = JobStaffModel::where([
            'id' => $id,
            'uid' => OA::$user->getId()
        ])->delete();
        if ($del == 1) {
            OA::Json(0, 'ok');
        } else {
            OA::Json(1, '删除失败');
        }
    }


    /**
     * 收到的投递列表
     */
    public function zhaopin_yplist(Request $request)
    {
        $page = $request->post('page', 0);
        $id = $request->post('id', 0);
        if ($id == 0) {
            OA::Json(1, '参数错误');
        }
        $model = JobStaffModel::where([
            'origin_id' => $id
        ])->where(
            'status','!=',JobStaffModel::status_tuihui
        )

            ->orderBy('id', 'desc')
            ->skip($page * 10)
            ->take(10)
            ->get();
        $list = [];
        foreach ($model as $vo) {
            $user = UserModel::getinfo($vo['uid']);
            $ziliao = UserStaffModel::where([
                'uid' => $vo['uid']
            ])->first();
            // var_dump($ziliao['education']);exit;
            $edu = '';
            if ($ziliao['education']) {
                $edu = UserStaffModel::educationTo($ziliao['education']);
            }

            $list[] = [
                'id' => $vo['id'],
                'uid' => $vo['uid'],
                'jiguang_id' =>JMessageApi::idToJiguang($vo['uid']),
                'status' => JobStaffModel::getStatus($vo['status']),
                'status_code' => $vo['status'],
                'created_at' => Fun::date($vo['created_at']),
                'user' => [
                    'name' => $user['name'],
                    'head' => $user['head'],
                    'xingming' => $ziliao['realname'] ?? '',
                    'sex' => UserModel::sexTo($ziliao['sex']),
                    'education' => $edu,
                    'salary' => (int)$ziliao['salary'],
                ]
            ];
        }
        OA::Json(0, $list);
    }


    /**
     * 通知该投递者来应聘
     */
    public function jobyingpin(Request $request)
    {
        $id = $request->post('id');
        $uid = OA::$user->getId();
        $jianliOne = JobStaffModel::where('id', $id)
            ->select([
                'id', 'uid', 'cid', 'origin_id', 'status'
            ])
            ->first();
        if (!$jianliOne) {
            OA::Json(1, '该简历不存在,或者系统错误');
        }
        if ($jianliOne['cid'] != $uid) {
            OA::Json(1, '权限错误,无权修改该投递信');
        }
        $jianliOne->status = JobStaffModel::status_wancheng;
        $gangweiOne = JobsCompanysModel::where([
            'id' => $jianliOne['origin_id'],
            'cid' => $uid
        ])->select([
            'id', 'company_name', 'work_hour'
        ])
            ->first();
        if (!$gangweiOne) {
            OA::Json(1, '该岗位消息不存在,或者系统错误');
        }
        $jianliOne->save();
        JMessageApi::SendMsg($jianliOne['uid'],
            '您向(' . $gangweiOne['company_name'] . ')投递的简历,已经通过了,请您在工作日(' . $gangweiOne['work_hour'] . ')来面试');
        OA::Json(0, 'ok');
    }

    /**
     * 退回用户的投递
     */
    public function jobtuihui(Request $request)
    {
        $id = $request->post('id');
        $uid = OA::$user->getId();
        $jianliOne = JobStaffModel::where('id', $id)
            ->select([
                'id', 'uid', 'cid', 'origin_id', 'status'
            ])
            ->first();
        if (!$jianliOne) {
            OA::Json(1, '该简历不存在,或者系统错误');
        }
        if ($jianliOne['cid'] != $uid) {
            OA::Json(1, '权限错误,无权修改该投递信');
        }
        $jianliOne->status = JobStaffModel::status_tuihui;
        $gangweiOne = JobsCompanysModel::where([
            'id' => $jianliOne['origin_id'],
            'cid' => $uid
        ])->select([
            'id', 'company_name', 'work_hour'
        ])
            ->first();
        if (!$gangweiOne) {
            OA::Json(1, '该岗位消息不存在,或者系统错误');
        }
        $jianliOne->save();
        JMessageApi::SendMsg($jianliOne['uid'],
            '您向(' . $gangweiOne['company_name'] . ')投递的简历,很抱歉,该企业拒绝了您的面试');
        OA::Json(0, 'ok');
    }


    /**
     * 退回用户的投递
     */
    public function getjianli(Request $request)
    {
        $id = $request->post('id', '');
        $StaffModel = new StaffModel();
        $select = [
            'realname as name',//姓名
            'sex', //性别：1，男；2女
            'birthday',
            'education', //最高学历：1小学；2初中；3高中/中专/专科；4本科；5研究生；6博士；7其他
            'weight', //体重
            'political_status',//政治面貌：1群众；2团员；3党员
            'native_place', //籍贯
            'nationality', //民族
            'marriage', //婚姻状况
            'house',//居住情况
            'image',//形象照片
            //  'idcard',//身份证号
            'household_address',//户口地址
            'residential_address',
            'contact_person',//紧急联系人
            'contact_phone',//紧急联系电话
            'skill',//专业技能
            'hobby',//兴趣爱好
            'image',///形象照片
            'salary',//期望月薪

            'job_str',///职位名称
            'uid'
        ];
        $staff = UserStaffModel::where('uid', $id)->select($select)->first();
        if (!$staff) {
            OA::Json(1, '没有基本数据或者参数错误');
        }
        if(!OA::$user->yunxuZhaopin()&&$staff['uid']!=OA::$user->getId()){
            OA::Json(25,'您没有启用公司或者工厂权限,无法查看该简历');
        }

        $userinfo = UserModel::getinfo($id);
        if (!$userinfo) {
            OA::Json(1, '没有用户数据或者参数错误');
        }
        $kuozhan = UserStaffOptionModel::where('uid', $id)->select([
            'edu_bgs',
            'work_historys', 'familys', 'comments'
        ])->first();
        $data = $staff->toArray();
        $data['education'] = UserStaffModel::educationTo($data['education']);
        $zhengzhimianmao = $StaffModel->getPolitics();
        $Marrys = $StaffModel->getMarrys();
        $data['political_status'] = $zhengzhimianmao[$data['political_status']] ?? '';
        $data['marriage'] = $Marrys[$data['marriage']] ?? '';
        $data['sex'] = UserModel::sexTo($data['sex']);
        $data['age'] = $this->ageByBirthday($data['birthday']);
        $data['phone'] = $userinfo['phone'];
        $data['head'] = $userinfo['head'];
        $data['image'] = Fun::pImg($data['image']);
        $data['kuozhan'] = null;
        $data['house']=UserStaffModel::tohouse($data['house']);
        $data['kuozhantest'] = null;
        $data['jiguang_id'] = JMessageApi::idToJiguang($data['uid']);
        if ($kuozhan) {
            $kz = $kuozhan->toArray();
            if ($kz['comments']) {
                $kz['comments'] = json_decode($kz['comments'], true);
            }
            if ($kz['edu_bgs']) {
                $kz['edu_bgs'] = json_decode($kz['edu_bgs'], true);
            }
            if ($kz['work_historys']) {
                $kz['work_historys'] = json_decode($kz['work_historys'], true);
            }
            $data['kuozhan'] = $kz;
        }

        OA::Json(0, $data);
    }


    protected function ageByBirthday($birthday)
    {
        $birthdayTime = strtotime($birthday);
        $year = date('Y', $birthdayTime);
        $age = date('Y') - $year;
        return $age;
    }


    /**
     * 修改招聘状态,或者删除
     * 参数: type:fabu,xiajia,delete;分别表示发布,下架,删除 id:岗位的id 返回:ok
     */
    public function upJobStatus(Request $request)
    {
        $type = $request->post('type');
        if ($type != 'fabu' && $type != 'xiajia' && $type != 'delete') {
            OA::Json(1, '参数错误');
        }
        $id = $request->post('id');
        $jobs = JobsCompanysModel::where([
            'id' => $id,
            'cid' => OA::$user->getId()
        ])->select([
            'id', 'cid', 'status', 'del'
        ])
            ->first();
        if (!$jobs) {
            OA::Json(1, '参数错误,或者无权限');
        }
        if ($type == 'fabu') {
            $jobs->status = JobsCompanysModel::status_fabuzhong;
        } elseif ($type == 'xiajia') {
            $jobs->status = JobsCompanysModel::status_xiajia;
        } elseif ($type == 'delete') {
            $jobs->status = JobsCompanysModel::status_xiajia;
            $jobs->del = 1;
        }
        if ($jobs->save()) {
            OA::Json(0, 'ok');
        } else {
            OA::Json(1, '系统错误,请稍候再试');
        }

    }


    /**
     *
     */
    public function jianli_list(Request $request)
    {
        $job = $request->post('job', '');
        $page = $request->post('page', 0);
        if (empty($job)) {
            $find = UserStaffModel::where([
                'shenhe' => UserStaffModel::shenhe_tongguo,
                'visible' => UserStaffModel::visible_show
            ]);
        } else {
            $find = UserStaffModel::where([
                'job' => $job,
                'shenhe' => UserStaffModel::shenhe_tongguo,
                'visible' => UserStaffModel::visible_show
            ]);
        }

        $list = $find->select([
            'uid',
            'realname',
            'sex',
            'education',
            'image',
            'salary',
            'skill',
            'job_str',
            'residential_address'
        ])
            ->orderBy('id', 'desc')
            ->skip($page * 10)
            ->take(10)
            ->get()->toArray();
        foreach ($list as $key => $v) {
            $user = UserModel::getinfo($v['uid']);
            $list[$key]['education'] = UserStaffModel::educationTo($v['education']);//学历
            $list[$key]['sex'] = UserModel::sexTo($v['sex']);
            $list[$key]['name'] = $user['name'];
        }
        OA::Json(0, $list);
    }


}